<!--
 * @Author: zqg
 * @Date: 2021-01-11 00:48:55
 * @LastEditors: zqg
 * @LastEditTime: 2021-03-15 17:18:41
 * @Description: 新增/编辑绩效规则
-->
<template>
  <base-layout>
    <template #searchPanel>
      <el-row>
        <el-col>绩效规则基础信息</el-col>
      </el-row>
      <el-divider content-position="center"></el-divider>
      <el-form
        :inline="true"
        ref="formRef"
        :model="addRulesQuery"
        :rules="rules"
        label-width="120px"
        label-position="right"
        :disabled="disabledForm"
      >
        <el-form-item
          label="绩效规则名称:"
          prop="performanceName"
        >
          <el-input
            v-model="addRulesQuery.performanceName"
            placeholder="请填写绩效规则名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="绩效规则门店:"
          prop="storeId"
        >
          <el-select
            v-model="addRulesQuery.storeId"
            placeholder="请选择门店"
          >
            <el-option
              v-for="item in stores"
              :key="item.id"
              :label="item.storeName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="绩效考核职位:"
          prop="assessRoleId"
        >
          <role-select
            v-model="addRulesQuery.assessRoleId"
            placeholder="请选择职位"
          />
        </el-form-item>
        <el-form-item
          label="指标类型:"
          prop="pointerType"
        >
          <el-select
            v-model="addRulesQuery.pointerType"
            placeholder="请选择指标类型"
          >
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生效月份:">
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-date-picker
                v-model="addRulesQuery.startTime"
                type="month"
                value-format="yyyy-MM"
                placeholder="选择生效开始月份"
              />
            </el-form-item>
          </el-col>
          <el-col
            class="line"
            :span="2"
          >至</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="addRulesQuery.endTime"
                type="month"
                value-format="yyyy-MM"
                placeholder="选择生效结束月份"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
    </template>
    <template #contentPanel>
      <el-form :disabled="disabledForm">
        <el-row>
          <el-col :span="20">绩效规则列表</el-col>
          <el-col
            :span="4"
            class="add-rules"
          >
            <el-button
              icon="el-icon-plus"
              type="primary"
              @click="addRules"
            >添加规则</el-button>
          </el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <data-table
          :value="tablePageList"
          :total-count="addRulesQuery.jxgzList.length"
          :has-action="true"
          :table-column-attributes="tableColumnAttributes"
          :width="160"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #action="{index}">
            <i
              class="el-icon-info"
              title="查看"
              style="cursor: pointer;"
              @click="viewRules(pageSize * (currentPage - 1) + index)"
            ></i>
            <i
              class="el-icon-edit"
              title="编辑"
              style=" margin-left: 20px;cursor: pointer"
              @click="eidtRules(pageSize * (currentPage - 1) + index)"
            ></i>
            <i
              class="el-icon-delete"
              title="删除"
              style="color:red; margin-left: 20px;cursor: pointer"
              @click="deleteRules(pageSize * (currentPage - 1) + index)"
            ></i>
          </template>
        </data-table>
        <div class="footer">
          <el-button
            type="success"
            @click="saveRules"
          >保存</el-button>
        </div>
        <addPerformanceDialog
          ref="addPerformanceDialog"
          :jxgzList="addRulesQuery.jxgzList"
          @save="jxgzListSave"
        />
      </el-form>
    </template>
  </base-layout>
</template>
<script>
import baseMixin from '@/mixins/base'
import { deepClone } from '@/utils/index'
import addPerformanceDialog from './components/addPerformanceDialog.vue'
import { getAllStore } from '@/api/after-sale/storehouseManage/transferManage'
import {
  addPerformance,
  performanceDetail,
  updatePerformance
} from '@/api/after-sale/personnel/performance'
export default {
  components: {
    addPerformanceDialog
  },
  mixins: [baseMixin({})],
  data() {
    return {
      // 指标类型
      options: ['经营指标', '管理指标', '超额奖励指标'],
      // 是否禁用（查看时禁用）
      disabledForm: false,
      addRulesQuery: {
        // 考核职位
        assessRoleId: '',
        // 无结束日期表示永久生效
        endTime: '',
        // 绩效规则id
        id: '',
        // 绩效规则列表
        jxgzList: [],
        // 绩效名称
        performanceName: '',
        // 指标类型
        pointerType: '',
        // 生效日期 yyyy-MM
        startTime: '',
        // 门店
        storeId: '',
        // 新增时不需要
        storeName: ''
      },
      // 门店列表
      stores: [],
      rules: {
        // 考核职位
        assessRoleId: {
          required: true,
          message: '请选择职位'
        },
        // 绩效名称
        performanceName: {
          required: true,
          message: '请输入绩效名称'
        },
        // 指标类型
        pointerType: {
          required: true,
          message: '请选择指标类型'
        },
        // 生效日期 yyyy-MM
        startTime: {
          required: true,
          message: '请选择生效开始日期'
        },
        // 生效日期 yyyy-MM
        endTime: {
          required: true,
          message: '请选择生效结束日期'
        },
        // 门店
        storeId: {
          required: true,
          message: '请选择门店'
        }
      },
      tableColumnAttributes: [
        { name: '规则项', value: 'ruleName', type: 'text' },
        { name: '考核权重', value: 'weight', type: 'text' },
        { name: '备注', value: 'remark', type: 'text' }
      ]
    }
  },
  computed: {
    /**
     * @description: 当前类型分页规则列表
     * @param {*}
     * @return {*}
     */
    tablePageList() {
      return this.addRulesQuery.jxgzList.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      )
    }
  },
  created() {
    this.disabledForm = !!this.$route.query.diabled
    const rulesId = this.$route.query.rulesId || ''
    this.getAllStore()
    // 存在绩效规则id表示编辑/查看
    if (rulesId) {
      this.getPerformanceDetail(rulesId)
    }
  },
  methods: {
    /**
     * @description: 查看规则
     *  @param {Number} 规则下标索引
     * @return {*}
     */
    viewRules(index) {
      if (this.disabledForm) {
        return
      }
      this.$refs.addPerformanceDialog.open(true, index)
    },
    /**
     * @description: 编辑规则
     * @param {Number} 规则下标索引
     * @return {*}
     */
    eidtRules(index) {
      if (this.disabledForm) {
        return
      }
      this.$refs.addPerformanceDialog.open(false, index)
    },
    /**
     * @description: 删除规则
     * @param {any} 规则详情
     * @return {*}
     */
    deleteRules(index) {
      if (this.disabledForm) {
        return
      }
      const list = this.addRulesQuery.jxgzList || []
      list.splice(index, 1)
      const currentPageAll = Math.ceil(list.length / this.pageSize) || 1;
      if (currentPageAll < this.currentPage) {
        this.currentPage = this.currentPage - 1
      }
    },
    /**
     * @description: 添加规则
     * @param {*}
     * @return {*}
     */
    addRules() {
      this.$refs.addPerformanceDialog.open(false)
    },
    /**
     * @description: 新增、编辑规则保存回调
     * @param {Object} 绩效规则
     * @param {Number} 规则下标索引
     * @return {*}
     */
    jxgzListSave(info, editIndex = -1) {
      if (editIndex === -1) {
        this.addRulesQuery.jxgzList.push(info)
      } else {
        this.$set(this.addRulesQuery.jxgzList, editIndex, info)
      }
    },
    /**
     * @description: 保存绩效规则
     * @param {*}
     * @return {*}
     */
    saveRules() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const param = deepClone(this.addRulesQuery)
          let errorMsg = ''
          if (!param.jxgzList.length) {
            errorMsg = '请添加规则'
          } else if (param.jxgzList) {
            const sum = param.jxgzList.reduce((l, t) => {
              return l + Number(t.weight)
            }, 0)
            errorMsg = sum !== 100 ? '所有的规则的考核权重相加必须等于100%' : ''
          }
          if (errorMsg) {
            this.$message.error(errorMsg)
            return
          }

          param.jxgzList.forEach(item => {
            item.khList = item.khList.map(key => {
              // 0是普通 1是配件  2是项目
              if (key.ruleType === 1) {
                key.assessValue = key.chooseAccessoriesInfo.id
              }
              if (key.ruleType === 2) {
                key.assessValue = key.chooseProjectInfo.id
              }
              // 删除前端自己使用的字段
              delete key.chooseAccessoriesInfo
              delete key.chooseProjectInfo
              !key.id && delete key.id
              return key
            })
            item.weight = Number(item.weight)
            return item
          })
          if (param.id) {
            updatePerformance(param).then(res => {
              let { success } = res
              if (success) {
                this.$message.success('保存成功')
                this.toPerformancePage()
              }
            })
          } else {
            delete param.id
            addPerformance(param).then(res => {
              let { success } = res
              if (success) {
                this.$message.success('保存成功')
                this.toPerformancePage()
              }
            })
          }
        }
      })
    },
    /**
     * @description: 去绩效管理首页
     * @param {*}
     * @return {*}
     */
    toPerformancePage() {
      this.$router.push({
        path: '/personnel/index'
      })
    },
    /**
     * @description: 获取所有门店
     * @param {*}
     * @return {*}
     */
    async getAllStore() {
      let { data } = await getAllStore()
      this.stores = data
    },
    /**
     * @description: 获取绩效规则详情
     * @param {Number} 规则id
     * @return {*}
     */
    async getPerformanceDetail(rulesId) {
      performanceDetail(rulesId).then(res => {
        const { success, data } = res
        if (success && data) {
          this.addRulesQuery = data
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  padding: 0;
}
.line {
  text-align: center;
}
.add-rules {
  text-align: right;
}
.footer {
  margin-top: 20px;
  text-align: right;
}
</style>
